// pages/chkDate/chkDate.js
import {request} from '../../request/index.js'
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';
var QQMapWX = require("../../utils/qqmap-wx-jssdk.min");
var qqmapsdk;
import Notify from '../../vant/dist/notify/notify'
import Dialog from '../../vant/dist/dialog/dialog'
var util = require('../../utils/jingweiduzhuanhuan')  
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dgeList:[],
    dgeName:'',
    address:'',
    jiazai: false
  },
 onClose(event) {
   var dgeId = event.currentTarget.dataset.dgeid
   console.log(dgeId)
    const { position, instance } = event.detail;
    let that = this
    switch (position) {
      case 'left':
      case 'cell':
      case 'outside':
        instance.close();
        break;
      case 'right':
        Dialog.confirm({
          message: '您确定要删除该隐患吗？',
        }).then(() => {
          that.DelDge(dgeId)
          instance.close();
        })
        .catch(() => {
          instance.close();
        });
    }
  },
  async DelDge (dgeId){
    const res = await request({
      url: '/danger/delete/' + dgeId,
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      method: "delete",
    })
    console.log(res)
    if (res.data.status !== 200){
      var title = res.data.msg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
      if (title == '您还未登录'){
         wx.reLaunch({
          url: '/pages/index/index',
        })
      }
    }
    else{
      wx.showToast({
        title: '删除成功',
        icon: 'none',
        duration: 2000
      })
      this.getDgeList(true)
    }
  },
  cancel(){
    // console.log(2)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qqmapsdk = new QQMapWX({
      key: 'TUHBZ-ZPFKU-XQAVA-BC4M4-ER4IZ-BXBLL'
    });
    this.getDgeList(false)
  },
  // 导航
  goToAddress (event){
    var lat = event.currentTarget.dataset.dgelat
    var lng = event.currentTarget.dataset.dgelng
    var dgeName = event.currentTarget.dataset.dgename
    this.jingWeiduToDiZhi(lat,lng,'goto')
    let that = this
    wx.getLocation({
      type:'gcj02', 
      success: function (res) {
        console.log(res.latitude); console.log(res.longitude);
        var result = util.transformFromBaiduToGCJ(lat,lng)
        wx.openLocation({
          latitude: result.latitude,
          longitude: result.longitude, 
          // scale: 8, // 缩放比例
          name: dgeName,
          address:that.data.address,
          success:function(r){
            console.log(r)
          }
        })
      }
    })
    
  },
  // 获取该供电局的隐患
  async getDgeList(refresh){
      const res = await request({
      url: '/danger/findAll/',
      // 上报已审核
      // url: '/danger/findByStatus/' + 'yes',
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      method: "get",
      success: function(res) {
        console.log(res)
      }
    })
    console.log(res)
    if (res.data.status !== 200){
      var title = res.data.msg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
      if (title === '您还未登录'){
        wx.reLaunch({
          url: '/pages/index/index',
        })
      }
    }
    else {
      if (! refresh) {
        wx.showLoading({
         title: '拼命加载中',
       })
     }
        var list= res.data.data
        var arr = []
        var nowTime = new Date()
        for (var i = 0; i<list.length ; ++i) {
          var item = list[i]
          if (item.dgeStatus === 'done' || item.dgeStatus === 'no' || item.dgeStatus === 'fail'){
            continue;
          }
          // 上报隐患通过
          if(item.chkTime){
              var time = item.chkTime.substring(0,19).replace(/-/g,'/')
              var date = new Date(time)
              nowTime = new Date(nowTime.getFullYear(), nowTime.getMonth(), nowTime.getDate());
              date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
              const diff = nowTime.getTime() - date.getTime(); //目标时间减去当前时间
              var Countdown =item.dgeCycle - diff / (24 * 60 * 60 * 1000)  ;  //计算当前时间与结束时间之间相差天数
              // console.log(Countdown)
              arr.push({Countdown:Countdown,item})
          }
          // 上报隐患未通过
          else {
              Countdown = null
          }
          // arr.push({Countdown:Countdown,item})
      }
      console.log(arr)
      if (refresh) {
        this.setData({
          dgeList: arr,
          jiazai: true
        },wx.stopPullDownRefresh({
          success: (res) => {},
        }))
      }
      else{
        this.setData({
          dgeList: arr,
          jiazai: true
        },wx.hideLoading({
          success: (res) => {},
        }))
      }
     
  }
  },
  ToSee: function(event){
    var lat = event.currentTarget.dataset.dgelat
    var lng = event.currentTarget.dataset.dgelng
    console.log(lat,lng)
    this.jingWeiduToDiZhi(lat,lng,'tosee')
  },
  // 经纬度转换成地址
jingWeiduToDiZhi(latitude,longitude,type) {
  let that = this;
  // 调用接口
  qqmapsdk.reverseGeocoder({
    location: {
      latitude: latitude ? latitude : null,
      longitude: longitude ? longitude : null
    },
    success: function(res){
      // console.log(res);
      // let tempData = res.result.address_component;
      if (type === 'goto'){
        that.setData({
        address: res.result.address
      })
      }
      else{
          Notify({ type: 'primary', message: res.result.address });
      }
      //   that.setData({
      //   address: res.result.address,
      //   // address: res.result.formatted_addresses.recommend,
      // },() => {
        
      // });
      
      
    },
    fail: function(error) {
      console.log("err")
      console.error(error);
    },
    complete: function(res) {
      // console.log(res);
    }
  })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getDgeList(true)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})